﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace db_util {
	public class mysql_helper {


		private static string mysql_conn_str = connection_string.ConnectionString;


		private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, string cmdText, MySqlParameter[] cmdParms) {
			if (conn.State != ConnectionState.Open)
				conn.Open();
			cmd.Connection = conn;
			cmd.CommandText = cmdText;
			if (cmdParms != null) {
				foreach (MySqlParameter parm in cmdParms)
					cmd.Parameters.Add(parm);
			}
		}

		public static int ExecuteNonQuery(string cmdText, MySqlParameter[] cmdParms) {
			using (var cmd = new MySqlCommand()) {
				using (var conn = new MySqlConnection(mysql_conn_str)) {
					PrepareCommand(cmd, conn, cmdText, cmdParms);
					int val = cmd.ExecuteNonQuery();
					cmd.Parameters.Clear();
					conn.Close();
					return val;
				}
			}
		}

		public static MySqlDataReader GetDataReader(string cmdText, MySqlParameter[] cmdParms) {
			var cmd = new MySqlCommand();
			var conn = new MySqlConnection(mysql_conn_str);
			try {
				PrepareCommand(cmd, conn, cmdText, cmdParms);
				MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
				cmd.Parameters.Clear();
				return reader;
			} catch {
				conn.Close();
				throw;
			}
		}
	}
}
